package com.jxmdkt.model;

import java.sql.SQLException;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

@SuppressWarnings("serial")
public class UinfoModel  extends Model<UinfoModel>{
	public static UinfoModel dao=new UinfoModel();
		
	public Page<UinfoModel> findAll(int pageNumber, int pageSize){
		return paginate(pageNumber, pageSize,"select * "," from uinfo_t order by datetime desc,cardno asc ");
	}
	
	public Object query(String cardno,String phoneno){
		UinfoModel model=findById(cardno);
		if(model==null||!phoneno.equals(model.get("phoneno")))
			return "你输入的信息有误！";
		else{
			return model;
		}
			
	}
	
	public String insert(UinfoModel uinfo) {
		UinfoModel model=findById(uinfo.getStr("cardno"));
		if(model==null){
			return "礼品卡号输入错误，请重新输入！";
		}else {
			if(model.getStr("used").equals("是")){
				return "used";
			}else {
				if(!uinfo.getStr("password").equals(model.getStr("password"))){
					return "密码错误，请重新输入！";
				}else {
					uinfo.set("used", "是");
					uinfo.update();
				}
			}
		}
		return null;
	}
	
	public boolean deliver(String[] s){
		final String[] strings=s;
		Db.tx(new IAtom() {
			
			@Override
			public boolean run() throws SQLException {
				for(String string:strings){
					if(!string.equals("")){
						Db.update("update uinfo_t set delivered='1' where cardno='"+string+"' " );
					}
				}
				return true;
			}
		});
		
		return true;
	}
	public Page<UinfoModel> query(int pagenow, int pagesize,String starttime,String endtime,String querycondition,String deliveredcondition){
		String sql="from uinfo_t  where 1=1 ";
		if(isNotEmpty(starttime))
			sql+=" and  datetime>='"+starttime+" 00:00:00' ";
		if(isNotEmpty(endtime))
			sql+=" and datetime<='"+endtime+" 23:59:59' ";
		if(!deliveredcondition.equals("0")){
			
			if(deliveredcondition.equals("1"))
				sql+=" and delivered='1' ";
			else {
				sql +=" and delivered='0' ";
			}
		}
		if(!querycondition.equals("0")){
			if(querycondition.equals("1"))
				sql+=" and used='是' ";
			else {
				sql +=" and used='否' ";
			}
		}
		sql+= "  order by datetime desc,cardno asc ";
		System.out.println(sql);
		return paginate(pagenow, pagesize, "select * ", sql);
	}
	private boolean isNotEmpty(String string){
		
		return string!=null&&!"".equals(string);		
	}
}
